//
//  FuncController.swift
//  HHSwift
//
//  Created by 华宏 on 2019/5/1.
//  Copyright © 2019年 huahong. All rights reserved.
//

import UIKit

class FuncController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "函数"

        
        //交换两数的值
        var a = 1
        var b = 2
        swapTwoInt( &a, &b)
        print("\(a),\(b)")
        
        
        //函数作为参数
        var arr:[Int] = []
        for _ in 0..<100 {
            arr.append(Int(arc4random()%1000))
        }
        
        //使用函数
       arr = arr.sorted(by: sorted)
        
      print("\(arr)")
       
        
        sendRequest(argc1: "5", arc2: "5", completionHandle: 3 < 5)
        
        
        let addMethod = add(input: 100)
        let output = addMethod(8)
        print("output:",output)
    }
    
//MARK:交换两数的值
    func swapTwoInt(_ a:inout Int , _ b:inout Int){
//        let t:Int = a
//        a = b
//        b = t
        (a,b) = (b,a)
    }
    
    
    
//MARK:函数作为参数
    func sorted(a:Int,_ b:Int) -> Bool {
        return a > b
    }
    
//MARK:返回函数类型和函数嵌套
    //方法的返回值没有使用,不警告
    @discardableResult
    func method1(weight:Int) -> Int {
        return 1 * weight
    }
    
    func method2(weight:Int) -> Int {
        return 2 * weight
    }
    
    func feeByPrice(price:Int,weight:Int) -> Int {
        
        func choose(weight:Int) -> (Int) -> Int {
            
            return weight <= 10 ? method1 : method2
        }
        
        let method = choose(weight: 12)
        return method(weight) + price * weight
        
    }
    
    
    // 可变长参数
    // 变长参数只能有一个
    // 变长参数不一定放在最后
    func addMul(numbers:Double ...) -> Double {
       
        var sum = 0.0
        for number in numbers {
            sum += number
        }
        
        return sum
        
    }
    
    
    
    func changeScores(scores: inout [Int] , by changeScore: (Int)->Int ){
        
        for (index,score) in scores.enumerated(){
            scores[index] = changeScore(score)
        }
    }
    
    func changeScore(score: Int) -> Int{
        return Int(sqrt(Double(score))*10)
    }
    
    
//    var scores = [65, 91, 45, 97, 87, 72, 33]
//    changeScores(scores: &scores, by: changeScore)
    
    //@autoclosure，可以让我们的表达式自动封装成一个闭包,只适用于这样的()->T无参闭包
    func sendRequest(argc1: String, arc2: String, completionHandle:@autoclosure () -> Bool) {
        if completionHandle() {
            print(argc1, arc2)
        }
    }
    
    
    //柯里化:多参数函数变成一连串单参数函数
    func add(input:Int) -> (Int) -> Int {
        return { value in
            return input + value
        }
    }
    
//    let addMethod = add(input: 100)
//    let output = addMethod(8)
    
    
}

